package com.droidclaimsurveyor;

import com.droidclaimsurveyor.activity.HomeActivity;
import com.droidclaimsurveyor.activity.MainActivity;
import com.droidclaimsurveyor.bl.DroidClaimBlService;
import com.droidclaimsurveyor.dto.ClaimInfoPKBlDto;
import com.droidclaimsurveyor.dto.SurveyorLocationBlDto;
import com.google.android.gms.maps.model.LatLng;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {

	private LatLng myLocation;
	Boolean isLooping = false;
	private double lat = 0;
	private double lng = 0;

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	Thread thread = new Thread() {
		int i = 0;

		@Override
		public void run() {
			DroidClaimBlService service = new DroidClaimBlService(null);
			SurveyorLocationBlDto dto = new SurveyorLocationBlDto();
			dto.setLatitude(lat);
			dto.setLongitude(lng);
			dto.setSessionId(MainActivity.getSessionId());
			dto.setStatus(true);
			try {
				if (isLooping) {
					while (isLooping) {
						LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
						Location location = locManager
								.getLastKnownLocation(LocationManager.GPS_PROVIDER);

						if (location != null) {
							lat = location.getLatitude();
							lng = location.getLongitude();
						}
						
						if(dto.getLatitude() != lat || dto.getLongitude() != lng)
						{
							dto.setLatitude(lat);
							dto.setLongitude(lng);
							service.UpdateSurveyorLocation(dto);
						}

						i++;
						Log.d("Loop", "loop =" + i + " lat:" + lat + " lng:"
								+ lng);
						sleep(1000);
					}

				} else {
					thread.stop();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	};

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		isLooping = true;
		thread.start();
		Toast.makeText(getApplication(), "Start Service", Toast.LENGTH_SHORT)
				.show();
		Log.d("TAG", "Service is started");
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		isLooping = false;
		Toast.makeText(getApplication(), "Stop Service", Toast.LENGTH_SHORT)
				.show();
		Log.d("TAG", "Service is stoped");
	}
}
